﻿using System.Linq;
using System.Windows;
using System.Windows.Media;

namespace DynamicGeometry
{
    public class Arrow : Polygon
    {
        public Arrow()
        {
            Shape.Stroke = null;
        }

        public override void UpdateVisual()
        {
            PointPair line = Line(0);
            LineBase parentLine = Dependencies.ElementAt(0) as LineBase;
            if (parentLine != null)
            {
                line = parentLine.OnScreenCoordinates;
            }

            Point p1 = line.P1;
            Point p2 = line.P2;
            double d = p1.Distance(p2);
            double arrowLength = ToLogical(16);
            double arrowWidth = 1.0 / 3;
            Point triangleBase = new Point(
                p2.X + (p1.X - p2.X) * arrowLength / d,
                p2.Y + (p1.Y - p2.Y) * arrowLength / d);

            // TODO: need to measure performance - I don't know what's 
            // faster - creating a new collection or emptying and
            // refilling the existing collection.
            // Gut feeling is that emptying and refilling should be faster
            // but I need to measure to confirm that.
            Shape.Points = new System.Windows.Media.PointCollection()
            {
                ToPhysical(p2),
                ToPhysical(new Point(
                    triangleBase.X + (p2.Y - triangleBase.Y) * arrowWidth,
                    triangleBase.Y + (triangleBase.X - p2.X) * arrowWidth)),
                ToPhysical(new Point(
                    triangleBase.X + (triangleBase.Y - p2.Y) * arrowWidth,
                    triangleBase.Y + (p2.X - triangleBase.X) * arrowWidth)),
            };
        }
    }
}
